<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input clearable @keyup.enter.native="handleFilter(1)" style="width: 200px;" class="filter-item" placeholder="订单号"
                v-model="orderVO.id">
      </el-input>
      <el-input clearable @keyup.enter.native="handleFilter(1)" style="width: 200px;" class="filter-item" placeholder="客户"
                v-model="orderVO.customerName">
      </el-input>
      <el-select clearable class="filter-item" style="width: 130px" v-model="orderVO.status" placeholder="状态">
        <el-option v-for="item in orderStatusList" :key="item.key" :label="item.display_name" :value="item.key">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter(1)">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"
                 icon="el-icon-edit">添加
      </el-button>
      <!--<el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">{{$t('table.export')}}</el-button>-->
      <el-checkbox class="filter-item" style='margin-left:15px;' @change='tableKey=tableKey+1' v-model="showReviewer">
        待收金额
      </el-checkbox>
    </div>
    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="玩命加载中" stripe
              style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-tabs :tab-position="tabPosition" type="border-card" @tab-click="tabsHandleClick">
            <el-tab-pane label="商品列表">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item>
                  <i class="el-icon-refresh" :click="tabsHandleClick"></i>
                </el-form-item>
                <el-form-item label="总数">
                  <span><el-tag type="success">{{ props.row.totalCount }}</el-tag></span>
                </el-form-item>
                <el-form-item label="总价">
                  <span>￥<el-tag type="success">{{ props.row.totalPrice }}</el-tag></span>
                </el-form-item>
                <el-form-item label="已收">
                  <span>￥<el-tag type="success">{{ props.row.totalReceipt }}</el-tag></span>
                </el-form-item>
              </el-form>
              <el-row :gutter="12">
                <el-col :span="8" :key="item.id" v-for="item in props.row.orderProducts">
                  <el-card shadow="hover" :body-style="{ padding: '0px' }" style="width: 200px;height: 200px">
                    <div style="padding: 13px; ">
                      <el-badge :value="item.productNum" class="item">
                        <el-tag type="success">{{ item.productName }}({{ item.productModel }})</el-tag>
                      </el-badge>
                      <div class="bottom clearfix" style="padding-top: 5px;">
                        <time class="time">￥{{ item.productPrice }}</time>
                        <el-button type="text" class="button">合计：￥{{ item.productTotalPrice }}</el-button>
                      </div>
                    </div>
                    <img src="https://www.baidu.com/img/bd_logo1.png?where=super" class="image">
                  </el-card>
                </el-col>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="快递信息">
              <el-form label-position="left" inline class="demo-table-expand">
                <el-form-item label="物流名称">
                  <span>{{ props.row.logisticsName }}</span>
                </el-form-item>
              <el-form-item label="物流单号">
                <span>{{ props.row.logisticsNo }}</span>
              </el-form-item>
              <el-form-item label="物流费用">
                <span>￥<el-tag type="success">{{ props.row.logisticsPrice }}</el-tag></span>
              </el-form-item>
                <el-form-item label="联系人">
                  <span>{{ props.row.contacts }}</span>
                </el-form-item>
                <el-form-item label="联系方式">
                  <span>{{ props.row.mobilePhone }}</span>
                </el-form-item>
                <el-form-item label="详细地址">
                  <span>{{ props.row.address }}</span>
                </el-form-item>
            </el-form>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>
      <el-table-column align="center" label="订单号" width="140">
        <template slot-scope="scope">
          <span>
            <router-link :to="{ path: 'order-create', params: { id: scope.row.id }}">{{scope.row.id}}</router-link>
          </span>
        </template>
      </el-table-column>

      <el-table-column min-width="200px" label="客户名">
        <template slot-scope="scope">
          <div  class="item">
          <el-badge :is-dot="scope.row.remark.length>0" >
            <el-popover v-if="scope.row.remark.length>0"
              placement="bottom"
              title="备注"
              width="200"
              trigger="hover"
              :content="scope.row.remark">
              <el-tag  slot="reference" size="medium">{{scope.row.customerName}}</el-tag>
            </el-popover>
            <el-tag v-else size="medium">{{scope.row.customerName}}</el-tag>
          </el-badge>
          <el-tag size="medium" v-if="scope.row.receiptType == '快递'" type="info">{{scope.row.receiptType}}</el-tag>
            <el-tag size="medium"  v-if="scope.row.receiptType == '自取'"  type="warning">{{scope.row.receiptType}}</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" v-if="showReviewer===true" label="应收-实收=待收" min-width="200px" >
        <template slot-scope="scope">
          <span>{{ scope.row.totalPrice }}</span>
          <span> - </span>
          <el-button type="text" @click="setCurrentPrice(scope.row)">{{ scope.row.totalReceipt }}</el-button>
          <span> = </span>
          <el-button type="text"  >￥{{ scope.row.totalPrice-scope.row.totalReceipt }}</el-button>
        </template>
      </el-table-column>

      <el-table-column align="center" label="物流信息" width="130">
        <template slot-scope="scope">
          <el-popover v-if="scope.row.contacts!=''" trigger="click" placement="top">
            <p>联系人: {{scope.row.contacts}}</p>
            <p>电话: {{scope.row.mobilePhone}}</p>
            <p>地址: {{scope.row.address}}</p>
            <p>物流: {{scope.row.logisticsName}}</p>
            <p>快递单号: {{scope.row.logisticsNo}}</p>
            <div slot="reference" class="name-wrapper">
               <span class="svg-container" v-if="scope.row.logisticsNo!==''&&scope.row.logisticsNo!=undefined">
          <svg-icon icon-class="express"></svg-icon>
          </span>
              <el-tag size="medium">{{scope.row.contacts}}</el-tag>

            </div>

          </el-popover>

        </template>
        <!--
                <template  v-if="scope.row.logisticsNo!=''" slot-scope="scope">
                  <el-tooltip placement="top">
                    <div slot="content">{{scope.row.logisticsName}}</div>
                    <el-tag>{{scope.row.logisticsNo}}</el-tag>
                  </el-tooltip>
                </template>-->
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="130">
        <template slot-scope="scope">
          <el-dropdown trigger="click" @command="handleCommand">
            <el-tag :type="scope.row.status | statusFilter">{{scope.row.status | parseOrderStatus2Name}}<i
              class="el-icon-arrow-down el-icon--right"></i></el-tag>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in orderStatusList" :key="item.key" :command="item.key" :orderRow="scope.row" :orderId="scope.row.id"
                                :disabled="item.key==scope.row.status?true:false">{{item.display_name}}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
      <el-table-column width="150px" align="center" label="时间">
        <template slot-scope="scope">
          <span>{{scope.row.orderDate | parseTime}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" v-if="scope.row.status===0" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="listQuery.pageNum" :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" min-width="900px" center>
      <order-create  style="
    padding-bottom: 0px;
    padding-top: 0px;
    padding-right: 0px;
    padding-left: 0px;
"  @refreshList="handleFilter(listQuery.pageNum)" ref="orderView" :createVisable="dialogFormVisible" :orderId="orderId"></order-create>
    </el-dialog>
    <el-dialog title="收款" :visible.sync="dialogPriceVisible"  width="300px">
      <el-form ref="priceInfoForm" :model="receiptInfo" label-width="80px">
        <el-form-item label="收款金额"  prop="totalReceipt" >
          <el-input v-model.number="receiptInfo.totalReceipt" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPriceVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReceipt('logisticsInfoForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="收货地址" :visible.sync="dialogSendFormVisible" width="400px">
      <el-form ref="logisticsInfoForm" :model="logisticsInfo" label-width="80px">
        <el-form-item label="物流名称"  prop="logisticsName">
          <el-input v-model.number="logisticsInfo.logisticsName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流单号"  prop="logisticsNo">
          <el-input v-model.number="logisticsInfo.logisticsNo" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="物流费用"  prop="logisticsPrice">
          <el-input v-model.number="logisticsInfo.logisticsPrice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系人">
          <el-input v-model="logisticsInfo.contacts" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="logisticsInfo.mobilePhone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="详细地址">
          <el-input v-model="logisticsInfo.address" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogSendFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="logisticsSubmit('logisticsInfoForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .item {
    margin: 5px;
    margin-right: 40px;
  }
  .time {
    font-size: 13px;
    color: #999;
  }

  .bottom {
    /* margin-top: 13px;*/
    line-height: 12px;
  }

  .button {
    padding: 0;
    float: right;
  }

  .image {
    width: 100%;
    display: block;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }

  .clearfix:after {
    clear: both
  }
</style>

<script>
  import { fetchOrderList, updateOrderInfo } from '@/api/order'
  // import waves from '@/directive/waves' // 水波纹指令
  import { parseTime } from '@/utils'
  import orderCreate from './order-create'

  export const orderStatusList = [
    { key: '0', display_name: '新订单' },
    { key: '10', display_name: '已审核' },
    { key: '20', display_name: '采购中' },
    { key: '30', display_name: '已投递' },
    { key: '40', display_name: '已完成' }
  ]
  const calendarTypeKeyValue = orderStatusList.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})
  export default {
    name: 'order-list',
    components: {
      'order-create': orderCreate
    },
    data() {
      return {
        receiptInfo: {
          id: '',
          totalReceipt: 0
        },
        dialogSendFormVisible: false, // 物流窗口
        entexpands: [],
        tabPosition: 'top',
        orderId: '',
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          pageNum: 1,
          pageSize: 20
        },
        orderVO: {
          id: '',
          customerName: '',
          contacts: '',
          status: '',
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        orderStatusList,
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        logisticsInfo: {
          logisticsName: '',
          logisticsNo: '',
          logisticsPrice: '',
          contacts: '',
          mobilePhone: '',
          address: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        dialogPriceVisible: false,
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    filters: {
      parseTime(time) {
        return parseTime(time)
      },
      statusFilter(status) {
        // 订单状态 0 新订单 10 已审核 20 采购中 30 已投递 40 已完成
        const statusMap = {
          0: 'success',
          10: '',
          20: 'warning',
          30: 'danger',
          40: 'info'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      },
      parseOrderStatus2Name(code) {
        if (code.length === 0) {
          return null
        }
        const statusMap = {
          0: '新订单',
          10: '已审核',
          20: '采购中',
          30: '已投递',
          40: '已完成',
          99: '作废'
        }
        return statusMap[code]
      }
    },
    created() {
      this.getList()
    },
    methods: {
      setCurrentPrice(row) {
        this.receiptInfo.totalReceipt = row.totalReceipt
        this.receiptInfo.id = row.id
        this.dialogPriceVisible = true
      },
      submitReceipt() {
        if (this.receiptInfo.totalReceipt === 0 || this.receiptInfo.totalReceipt === null || this.receiptInfo.totalReceipt === undefined) {
          this.$message({
            message: '请输入金额',
            type: 'error'
          })
          return
        }
        this.setOrderInfo(this.receiptInfo)
      },
      /**
       * 状态变更
       * @param command
       * @param orderId
       */
      handleCommand(command, dataInfo) {
        const row = dataInfo.$attrs.orderRow
        if (command === '30') {
          // 投递
          this.logisticsInfo.id = row.id
          this.logisticsInfo.status = command
          this.logisticsInfo.contacts = row.contacts
          this.logisticsInfo.mobilePhone = row.mobilePhone
          this.logisticsInfo.address = row.address
          this.logisticsInfo.logisticsNo = row.logisticsNo
          this.dialogSendFormVisible = true
        } else {
          this.setOrderInfo({ id: row.id, status: command })
        }
      },
      logisticsSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.setOrderInfo(this.logisticsInfo)
            this.$refs[formName].clearValidate()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      setOrderInfo(vo) {
        updateOrderInfo(vo).then(response => {
          this.$message({
            message: '变更成功',
            type: 'success'
          })
          this.dialogSendFormVisible = false
          this.dialogPriceVisible = false
          this.getList()
        })
      },
      getList() {
        this.listLoading = true
        fetchOrderList(this.listQuery, this.orderVO).then(response => {
          this.listLoading = false
          if (response.code !== 200) {
            this.$message({
              message: response.message,
              type: 'error'
            })
          }
          this.list = response.data.list
          this.total = response.data.total
        })
      },
      handleFilter(pageNum) {
        this.listQuery.pageNum = pageNum
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      tabsHandleClick(row) {
        console.log('触发了')
      },
      handleUpdate(row) {
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.orderId = row.id
        // this.$.refs.orderView.getOrder()
        // this.$nextTick(() => {
        //   this.$refs['dataForm'].clearValidate()
        // })
      },
      handleCreate() {
        this.orderId = ''
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
